package com.kmxd.ams.app.search.command;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kmxd.ams.client.archive.*;
import com.kmxd.ams.client.es.IDocumentEsSvc;
import com.kmxd.ams.client.jy.IAuthDatabaseSvc;
import com.kmxd.ams.client.jy.IAuthDetailsSvc;
import com.kmxd.ams.client.system.ISysUserSvc;
import com.kmxd.ams.client.system.vo.SysUserVO;
import com.kmxd.ams.core.common.constant.ArchControlConst;
import com.kmxd.ams.infra.jy.entity.AuthDatabase;
import com.kmxd.ams.infra.jy.entity.AuthDetails;
import java.util.*;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 检索权限控制
 *
 * @author zuolg
 */
@Slf4j
@Component
@AllArgsConstructor
public class SearchAuthCmd {
    private final IDocumentEsSvc documentEsSvc;
    private final IAuthDatabaseSvc authDatabaseSvc;
    private final IAuthDetailsSvc authDetailsSvc;
    private final ISysUserSvc sysUserSvc;

    /**
     * 获取控制条件
     *
     * @param userId
     * @return
     */
    public List<Integer> getAuthRangeByUser(Long userId) {
        SysUserVO sysUserVO = sysUserSvc.view(userId);
        if (ObjUtil.isNotEmpty(sysUserVO) && ObjUtil.equal(sysUserVO.getScopeArchiving(), "受控档案")) {
            return ListUtil.of(ArchControlConst.CTL_1, ArchControlConst.CTL_2, ArchControlConst.CTL_3);

        } else {
            return ListUtil.of(ArchControlConst.CTL_2);
        }
    }

    /**
     * 获取门类权限
     *
     * @param userId
     * @return
     */
    public List<Long> getArchTypeByUser(Long userId) {
        LambdaQueryWrapper<AuthDatabase> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AuthDatabase::getUserId, userId);
        List<AuthDatabase> list = authDatabaseSvc.list(queryWrapper);
        return list.stream().map(AuthDatabase::getArchivesId).collect(Collectors.toList());
    }

    /**
     * 获取档案权限
     *
     * @param userId
     * @return
     */
    public List<Long> getArchByUser(Long userId) {
        LambdaQueryWrapper<AuthDetails> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AuthDetails::getUserId, userId);
        List<AuthDetails> list = authDetailsSvc.list(queryWrapper);
        return list.stream().map(AuthDetails::getObjId).collect(Collectors.toList());
    }
}
